<template>
  <div class="shopcar-page" ref="shopcar_page">
    <div class="shopcar-box">
      <div class="shopcar-contain" v-show="hasCarShip">
        <div class="street-box" @click="toAddress">
          <span class="street-text">{{streetInfo}}</span>
        </div>
        <div class="cart-group">
          <div class="cart-head">
            <div class="cart-group-all">
              <span class="checkbox" :class="{checked:chooseAll}" @click.stop.prevent="selectAll"></span>
            </div>
            <div class="cart-group-title">
              <span>{{deliveryTime}}</span>
            </div>
            <div class="cart-ship-head">
              <span v-show="!isFreeShip">
                实付满{{shipPrice | money}}元包邮，还差{{freeShipPrice | money}}元
              </span>
              <span v-show="isFreeShip">
                免运费
              </span>
            </div>
          </div>
          <div class="cart-list">
            <div class="cart-item" v-for="(item,index) in shopCarInfo" :key="index">
              <div class="checkbox-wrapper">
                <span class="checkbox" :class="{checked:item.choose}" @click="selectThis(item)"></span>
              </div>
              <div class="item-content">
                <div class="item-image cart-item-image">
                  <img v-lazy="item.thumb" alt="">
                </div>
                <div class="item-info">
                  <div class="mess-title">{{item.title}}</div>
                  <div class="bom-price">
                    <span class="icon-unit">￥</span>
                    <span class="price-number">{{item.price | money}}</span>
                  </div>
                  <div class="cart-compontent">
                    <span class="reduce" @click.stop.prevent="reduceGoodsNum(item,$event)"></span>
                    <span class="txt">{{item.quantity}}</span>
                    <span class="add" @click.stop.prevent="addGoodsNum(item,$event)"></span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="price-list-panel">
            <div class="list item-board">
              <div class="title">商品总价</div>
              <div class="price-content">
                <span class="price-letter">￥{{goodsSumPrice | money}}</span>
              </div>
            </div>
            <div class="list item-board">
              <div class="title">运费
                <span class="tips">实付满{{shipPrice | money}}元包邮</span>
              </div>
              <div class="price-content">
                <span class="price-letter" v-show="!isFreeShip">￥{{shippingFee | money}}</span>
                <span class="price-letter" v-show="isFreeShip">免运费</span>
              </div>
            </div>
            <div class="list item-board">
              <div class="title"></div>
              <div class="price-content">
                <span class="total-info">总价</span>
                <span class="total-letter">￥{{totalPrice | money}}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="no-cart" v-show="noCarShip">
        <div class="no-cart-logo"></div>
        <div class="no-cart-info">
          <span class="no-cart-txt1">您还没有添加任何商品</span>
        </div>
      </div>
    </div>
    <div class="cart-footer" v-show="hasCarShip">
      <div class="price-num  price-left">
        <div class="checkbox-wrapper check-left">
          <span class="checkbox" :class="{checked:chooseAll}" @click.stop.prevent="selectAll"></span>
        </div>
        <span class="all">
          全选
        </span>
      </div>
      <div class="fot-price foot-info">
        <span class="total-price-box">
          <span>合计</span>
          <span class="total-price">￥{{totalPrice | money}}</span>
        </span>
        <span class="post-info">
          <span class="post-price" v-show="!isFreeShip">运费￥{{shippingFee | money}}</span>
          <span class="post-price" v-show="isFreeShip">免邮</span>
        </span>
      </div>
      <div class="fot-price foot-price">
        <div class="price-btn" @click="confirmOrder()">
          去结算
        </div>
      </div>
    </div>
    <footer-tab :iscur="tabView"></footer-tab>
  </div>
</template>

<script>
  /* eslint-disable */
  import Vue from 'vue'
  import BScroll from 'better-scroll'
  import store from '@/store/store'
  import {
    mapState,
    mapMutations,
    mapActions
  } from 'vuex'
  import {
    Button,
    Lazyload,
    Icon,
    Dialog,
    Toast
  } from 'vant'
  import {
    CODE,
    APIURI
  } from '#/common/js/apiConst'
  import FooterTab from '#/footer/footer'
  import CartControl from '#/cartcontrol/cartcontrol'
  import AddressList from '#/addressList/addressList'

  Vue.use(Button).use(Lazyload)

  export default {
    store,
    data() {
      return {
        tabView: 'shopcar',
        deliveryTime: '极速达',
        lave: '',
        shipPrice: 0,
        freeShipPrice: 0,
        goodsSumPrice: 0,
        totalPrice: 0,
        shippingFee: 0,
        isFreeShip: false,
        streetInfo: '您还未选择收货地址',
        chooseAll: true,
        shopCarInfo: [],
        hasCarShip: false,
        noCarShip: false
      }
    },
    components: {
      Icon,
      FooterTab,
      CartControl,
      AddressList
    },
    created() {
      this.$axios
        .get(APIURI + '/cart')
        .then(res => {
          res = res.data
          if (res.code === CODE) {
            if (res.data) {
              this.hasCarShip = true
              this.noCarShip = false
              this.shopCarInfo = res.data.list
              this.chooseAll = res.data.all_choose
              this.shipPrice = res.data.full
              this.isFreeShip = res.data.sfmy
              this.shippingFee = res.data.youfei
              this.goodsSumPrice = res.data.money
              this.totalPrice = res.data.total
              this.lave = res.data.lave

              if (this.shipPrice > this.goodsSumPrice) {
                this.freeShipPrice = this.shipPrice - this.goodsSumPrice
              } else {
                this.freeShipPrice = 0
              }
            } else {
              this.hasCarShip = false
              this.noCarShip = true
            }
            this.$nextTick(() => {
              this._initScroll()
            })
          } else {
            this.hasCarShip = false
            this.noCarShip = true
          }
        })
        .catch(function(err) {
          console.log(err)
        })

      this.getStreetInfo()

      this.countMoney(this.shopCarInfo)
    },
    computed: {
      ...mapState(['subCount', 'carGoods', 'street'])
    },
    methods: {
      ...mapMutations(['addGoods', 'delGoods']),
      ...mapActions(['addsubCount', 'reducesubCount']),
      _initScroll() {
        if (!this.shopcarScroll) {
          this.shopcarScroll = new BScroll(this.$refs.shopcar_page, {
            probeType: 3,
            scrollY: true,
            click: true
          })
        } else {
          this.shopcarScroll.refresh()
        }
      },
      toAddress() {
        this.$router.push({
          path: '/user/addresslist?source=shopcar'
        })
      },
      getStreetInfo() {
        this.streetInfo =
          JSON.parse(localStorage.state).street || '您还未选择收货地址'
        // let streetList = []
        // let streetInfo = ''
        // this.$axios
        //   .get(APIURI + '/address/2/0')
        //   .then(res => {
        //     res = res.data
        //     if (res.code === CODE) {
        //       streetList = res.data.list
        //       streetList = streetList.filter(el => {
        //         return el.stats === '1'
        //       })
        //       if (streetList.length) {
        //         streetInfo = streetList[0].address
        //       } else {
        //         streetInfo = '您还未选择收货地址'
        //       }
        //     }
        //   })
        //   .catch(function(err) {
        //     console.log(err)
        //   })
      },
      streetChange() {
        this.streetInfo = this.street
      },
      selectAll() {
        this.chooseAll = !this.chooseAll
        if (this.chooseAll) {
          this.shopCarInfo.forEach(el => {
            el.choose = true
          })
        } else {
          this.shopCarInfo.forEach(el => {
            el.choose = false
          })
        }
        this.countMoney(this.shopCarInfo)
        let param = this.chooseAll ? '1' : '0'
        this.$axios
          .get(APIURI + '/cart/check/all/' + param)
          .then(res => {
            res = res.data
            if (res.code === CODE) {
              // console.log(res.message)
            }
          })
          .catch(function(err) {
            console.log(err)
          })
      },
      selectThis(item) {
        item.choose = !item.choose
        let chechedArr = this.hasSelectAll(this.shopCarInfo)
        if (chechedArr.length === 1 && chechedArr[0] === true) {
          this.chooseAll = true
        } else {
          this.chooseAll = false
        }
        this.countMoney(this.shopCarInfo)
        this.$axios
          .get(APIURI + '/cart/check/' + item.id)
          .then(res => {
            res = res.data
            if (res.code === CODE) {
              // console.log(res.message)
            }
          })
          .catch(function(err) {
            console.log(err)
          })
      },
      countMoney(shopCarInfo) {
        let chooseData = shopCarInfo.filter(el => {
          return el.choose === true
        })
        if (chooseData.length === 0) {
          this.isFreeShip = true
          this.goodsSumPrice = 0
          this.totalPrice = 0
        } else {
          let sumPrice = 0
          chooseData.forEach(el => {
            sumPrice += el.price * el.quantity
          })
          this.goodsSumPrice = sumPrice
          if (this.goodsSumPrice >= this.shipPrice) {
            this.isFreeShip = true
            this.totalPrice = this.goodsSumPrice
          } else {
            this.isFreeShip = false
            this.freeShipPrice = this.shipPrice - this.goodsSumPrice
            this.totalPrice = this.goodsSumPrice + this.shippingFee
          }
        }
      },
      hasSelectAll(data) {
        let arr = []
        data.forEach(el => {
          arr.push(el.choose)
        })
        arr = [...new Set(arr)]
        return arr
      },
      addGoodsNum(item, event) {
        this.$axios
          .get(APIURI + '/cart/update/' + item.id)
          .then(res => {
            res = res.data
            if (res.code === CODE) {
              item.quantity = item.quantity + 1
              this.countMoney(this.shopCarInfo)
              this.addGoods(item)
            } else {
              Toast(res.msg)
              event.target.classList.add('gray')
            }
          })
          .catch(function(err) {
            console.log(err)
          })
      },
      reduceGoodsNum(item, event) {
        if (item.quantity > 1) {
          this.$axios
            .get(APIURI + '/cart/reduce/' + item.id)
            .then(res => {
              res = res.data
              if (res.code === CODE) {
                item.quantity = item.quantity - 1
                event.target.parentNode.lastChild.classList.remove('gray')
                this.delGoods(item)
                this.countMoney(this.shopCarInfo)
              }
            })
            .catch(function(err) {
              console.log(err)
            })
        } else {
          Dialog.confirm({
              title: '',
              message: '您确定删除该商品吗？'
            })
            .then(() => {
              // on confirm
              this.$axios
                .get(APIURI + '/cart/del/' + item.id)
                .then(res => {
                  res = res.data
                  if (res.code === CODE) {
                    item.quantity = 0
                    this.shopCarInfo = this.shopCarInfo.filter(el => {
                      return el.quantity != 0
                    })
                    this.countMoney(this.shopCarInfo)
                    this.delGoods(item)
                    if (Object.keys(res.data).length === 0) {
                      this.hasCarShip = false
                      this.noCarShip = true
                    }
                  }
                })
                .catch(function(err) {
                  console.log(err)
                })
            })
            .catch(() => {
              // on cancel
            })
        }
      },
      confirmOrder() {
        if (this.goodsSumPrice > 0) {
          this.$router.push({
            path: '/orderconfirm'
          })
        } else {
          Toast('请选择商品')
        }
      }
    },
    watch: {
      street: 'streetChange'
    },
    filters: {
      money: val => {
        val = val.toString().replace(/\$|\,/g, '')
        if (isNaN(val)) {
          val = '0'
        }
        let sign = val == (val = Math.abs(val))
        val = Math.floor(val * 100 + 0.50000000001)
        let cents = val % 100
        val = Math.floor(val / 100).toString()
        if (cents < 10) {
          cents = '0' + cents
        }
        for (var i = 0; i < Math.floor((val.length - (1 + i)) / 3); i++) {
          val =
            val.substring(0, val.length - (4 * i + 3)) +
            ',' +
            val.substring(val.length - (4 * i + 3))
        }

        return (sign ? '' : '-') + val + '.' + cents
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import './../common/scss/common.scss';
  @import './shopcar.scss';
</style>